package service

import (
	"iris-wms/apps/admin/web/dto/din"
	"iris-wms/apps/admin/web/dto/dout"
	"iris-wms/common/pkg/db"
	"iris-wms/common/pkg/db/dao"
)

var _ WmsInventoryService = (*wmsInventoryService)(nil)

type WmsInventoryService interface {
	QueryInventory(uint, uint) (*dout.WmsReportOfGoodsOut, error)
	QueryInventoryOfGoodsIdListAndWid([]uint, []uint) ([]*dout.WmsReportOfGoodsOut, error)
	QueryInventoryStockWarning(din.VxeTableIn) ([]*dout.WmsReportOfGoodsOut, int64, error)
}

func NewWmsInventoryService() *wmsInventoryService {
	return &wmsInventoryService{}
}

type wmsInventoryService struct{}

func (impl *wmsInventoryService) QueryInventory(goodsId, wid uint) (result *dout.WmsReportOfGoodsOut, err error) {
	q := dao.Use(db.GDB1).WmsReportOfGoodsOut
	result, err = q.QueryInentoryByGoodsIdAndWid(goodsId, wid)
	return
}

func (impl *wmsInventoryService) QueryInventoryOfGoodsIdListAndWid(goodsIdList, widList []uint) (rows []*dout.WmsReportOfGoodsOut, err error) {
	q := dao.Use(db.GDB1).WmsReportOfGoodsOut
	rows, err = q.
		Preload(q.Cate).
		Preload(q.Warehouse).
		QueryInentoryByGoodsIdListAndWid(goodsIdList, widList)
	return
}

func (impl *wmsInventoryService) QueryInventoryStockWarning(in din.VxeTableIn) (result []*dout.WmsReportOfGoodsOut, total int64, err error) {
	q := dao.Use(db.GDB1).WmsReportOfGoodsOut

	if err = q.UnderlyingDB().Raw(`
	SELECT COUNT(A.id) FROM wms_goods A left join
	(
	SELECT SUM(A.qty*A.mark) sum_qty, A.* FROM wms_inventory A WHERE A.status=1
	group by A.goods_id
	) B ON A.id = B.goods_id
	WHERE A.min_stock > B.sum_qty
	`).Count(&total).Error; err != nil {
		return nil, 0, err
	}
	result, err = q.QueryInventoryStockWarning(in.Offset(), in.PageSize)
	return
}
